package com.xuan.yrmanage.dao;


import com.xuan.yrmanage.domain.Permission;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.jdbc.SQL;

import java.util.List;

@Mapper
public interface PermissionMapper {

    //获取列表
    @SelectProvider(type = PermissionMapper.PermissionProvider.class, method = "findAll")
    @Results(id = "permissionMap", value = {
            @Result(column = "id", property = "id"),
            @Result(column = "name", property = "name"),
            @Result(column = "keyword", property = "keyword"),
            @Result(column = "description", property = "description"),
            @Result(column = "function_key", property = "functionKey"),
    })
    List<Permission> findAll(@Param("pageIndex") int pageIndex, @Param("pageSize") int pageSize, @Param("name") String name);

    //获取总数
    @SelectProvider(type = PermissionMapper.PermissionProvider.class, method = "getCount")
    int getCount(@Param("name") String name);

    //根据id 获取权限
    @Select( "select * from t_permission where id=#{id}" )
    @ResultMap( value = "permissionMap")
    Permission findById(@Param( "id" ) String id);

    //添加权限
    @Insert( "insert into t_permission (name,keyword,description,function_key) " +
            " values (#{name},#{keyword},#{description},#{functionKey})" )
    void add(Permission permission);

    //修改权限
    @Update( "update t_permission set name=#{name},keyword=#{keyword},description=#{description},function_key=#{functionKey}" +
            " where id=#{id}" )
    void edit(Permission permission);



    class PermissionProvider{

       public String findAll(@Param( "pageIndex" ) int pageIndex, @Param( "pageSize" )int pageSize, @Param( "name" )String name) {
           SQL sql = new SQL() {
               {
                   SELECT( "*" );
                   FROM( "t_permission" );
                   if (StringUtils.isNotEmpty( name )) {
                       WHERE( "name like \"%\" #{name}\"%\" or keyword like \"%\"#{name}\"%\"" );
                   }
               }
           };
           String sqlStr = sql.toString();
           if (pageIndex != 0 && pageSize != 0) {
               int start = (pageIndex - 1) * pageSize;
               sqlStr += " limit " + start + "," + pageSize;
           }

           return sqlStr;
       }

       public String getCount(@Param( "name" )String name) {
           SQL sql = new SQL() {
               {
                   SELECT( "count(*)" );
                   FROM( "t_permission" );
                   if (StringUtils.isNotEmpty( name )) {
                       WHERE( "name like \"%\" #{name}\"%\" or keyword like \"%\"#{name}\"%\"" );
                   }
               }
           };
           String sqlStr = sql.toString();
           return sqlStr;
       }

   }
}
